import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:yi_shop/components/store/activity.dart';
import 'package:yi_shop/components/store/baby.dart';
import 'package:yi_shop/components/store/good.dart';
import 'package:yi_shop/components/store/main.dart';
import 'package:yi_shop/components/store/new.dart';
import 'package:yi_shop/ui/keep_alive.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/radian.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

typedef SliverHeaderBuilder = Widget Function(
    BuildContext context, double shrinkOffset, bool overlapsContent);

class StoreHomeController extends GetxController with GetSingleTickerProviderStateMixin {
  late TabController controller;
  late ScrollController scrollController;
  List<String> tabs = ['首页', '宝贝', '新品', '好物', '活动'];

  List<String> list = ['综合', '销量', '新品', '价格'];

  RxInt typeIndex = 0.obs;

  RxDouble opacity = RxDouble(0);

  RxBool visible = RxBool(false);

  @override
  void onInit() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarBrightness: Brightness.light,
      statusBarIconBrightness: Brightness.light,
    ));
    controller = TabController(length: tabs.length, vsync: this);
    scrollController = ScrollController()
      ..addListener(() {
        final double t = clampDouble(scrollController.offset / 50, 0.0, 1.0);
        opacity.value = t;
        if (scrollController.offset > 50) {
          visible.value = true;
          return;
        }
        visible.value = false;
      });
    super.onInit();
  }

  @override
  void onClose() {
    scrollController.dispose();
    controller.dispose();
    super.onClose();
  }
}

class StoreHomePage extends GetView<StoreHomeController> {
  const StoreHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: controller.tabs.length,
        child: Scaffold(
          body: NestedScrollView(
            controller: controller.scrollController,
            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverAppBar(
                  pinned: true,
                  expandedHeight: 132,
                  automaticallyImplyLeading: false,
                  forceElevated: innerBoxIsScrolled,
                  flexibleSpace: FlexibleSpaceBar(
                    background: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                        ColorsUtils.rgba(249, 212, 35, 1),
                        ColorsUtils.rgba(248, 54, 0, 1)
                      ], stops: const [
                        0,
                        1.0
                      ], transform: GradientRotation(RadianUtils.angleToRadian(270)))),
                      child: Column(
                        children: [
                          Padding(
                            padding: EdgeInsets.only(top: Get.mediaQuery.padding.top),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '韩都衣舍旗舰店',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: StylesUtils.fontSize18,
                                      fontWeight: FontWeight.w700),
                                ),
                                Expanded(
                                    child: Wrap(
                                  spacing: 30,
                                  alignment: WrapAlignment.end,
                                  crossAxisAlignment: WrapCrossAlignment.center,
                                  children: [
                                    TextButton(
                                        onPressed: () {},
                                        style: ButtonStyle(
                                            minimumSize: const WidgetStatePropertyAll(Size(70, 30)),
                                            padding: const WidgetStatePropertyAll(EdgeInsets.zero),
                                            backgroundColor:
                                                const WidgetStatePropertyAll(Colors.white),
                                            alignment: Alignment.center,
                                            shape: WidgetStatePropertyAll(RoundedRectangleBorder(
                                                borderRadius: BorderRadius.circular(5)))),
                                        child: Text(
                                          '+关注',
                                          style: StylesUtils.customTextStyle(
                                              color: ColorsUtils.color8080,
                                              fontSize: StylesUtils.fontSize13),
                                        )),
                                    IconButton(
                                        onPressed: () {
                                          Get.back();
                                        },
                                        icon: const Icon(
                                          Icons.close,
                                          size: 12,
                                          color: Colors.white,
                                        ))
                                  ],
                                ))
                              ],
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(vertical: 10),
                            alignment: Alignment.centerLeft,
                            child: Wrap(
                              spacing: 15,
                              children: [
                                Text(
                                  '综合体验',
                                  style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorF2f2,
                                  ),
                                ),
                                SizedBox(
                                  width: 100,
                                  child: Wrap(
                                    spacing: 10,
                                    children: [
                                      for (var i = 0; i < 5; i++)
                                        const Icon(
                                          Icons.star,
                                          size: 11,
                                          color: Colors.white,
                                        ),
                                    ],
                                  ),
                                ),
                                Text(
                                  '粉丝数 2039万',
                                  style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorF2f2,
                                  ),
                                )
                              ],
                            ),
                          ),
                          Container(
                            color: Colors.transparent,
                            child: Row(
                              children: [
                                TextButton(
                                    onPressed: () {},
                                    style: ButtonStyle(
                                        fixedSize: const WidgetStatePropertyAll(Size(60, 30)),
                                        minimumSize: const WidgetStatePropertyAll(Size(60, 30)),
                                        padding: const WidgetStatePropertyAll(EdgeInsets.zero),
                                        alignment: Alignment.center,
                                        shape: WidgetStatePropertyAll(RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(15),
                                            side: BorderSide(
                                                color: ColorsUtils.parseColorFromHexString(
                                                    ColorsUtils.colorFfff))))),
                                    child: Text.rich(TextSpan(children: [
                                      const WidgetSpan(
                                          child: Icon(
                                            Icons.search_sharp,
                                            size: 15,
                                            color: Colors.white,
                                          ),
                                          alignment: PlaceholderAlignment.middle),
                                      TextSpan(
                                          text: ' 搜索',
                                          style: StylesUtils.customTextStyle(
                                              fontSize: StylesUtils.fontSize12,
                                              color: ColorsUtils.colorFfff))
                                    ]))),
                                Expanded(child: tabBar)
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    title: Obx(() => Visibility(
                          visible: controller.visible.value,
                          maintainAnimation: true,
                          maintainState: true,
                          child: Container(
                            padding: EdgeInsets.only(
                                left: 10, right: 10, top: Get.mediaQuery.padding.top),
                            child: Row(
                              children: [
                                IconButton(
                                    onPressed: () {},
                                    icon: Icon(
                                      Icons.search_rounded,
                                      size: 20,
                                      color: ColorsUtils.parseColorFromHexString(
                                          ColorsUtils.colorFfff),
                                    )),
                                Expanded(child: tabBar)
                                // Expanded(
                                //     child: ToolsUtils.getClientTabBar(
                                //         controller.tabs, controller.controller,
                                //         indicatorColor: ColorsUtils.colorFfff,
                                //         labelColor: ColorsUtils.colorFfff,
                                //         unselectedLabelColor: ColorsUtils.colorFfff,
                                //         isScrollable: false))
                              ],
                            ),
                          ),
                        )),
                  ),
                ),
                SliverVisibility(
                  sliver: SliverPersistentHeader(
                    delegate: _SliverHeaderDelegate.builder(
                        maxHeight: 40,
                        minHeight: 40,
                        builder: (c, shrinkOffset, overlapsContent) {
                          return Container(
                            height: 40,
                            padding: const EdgeInsets.symmetric(horizontal: 10),
                            alignment: Alignment.centerLeft,
                            decoration: overlapsContent
                                ? BoxDecoration(
                                    color:
                                        ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048))
                                : BoxDecoration(
                                    gradient: LinearGradient(colors: [
                                    ColorsUtils.rgba(249, 212, 35, 1),
                                    ColorsUtils.rgba(248, 54, 0, 1)
                                  ], stops: const [
                                    0,
                                    1.0
                                  ], transform: GradientRotation(RadianUtils.angleToRadian(270)))),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Wrap(
                                  spacing: 20,
                                  crossAxisAlignment: WrapCrossAlignment.center,
                                  alignment: WrapAlignment.start,
                                  children: controller.list
                                      .asMap()
                                      .map((key, value) => MapEntry(
                                          key,
                                          Obx(() => TextButton(
                                                onPressed: () {
                                                  controller.typeIndex.value = key;
                                                },
                                                style: ButtonStyle(
                                                    minimumSize:
                                                        const WidgetStatePropertyAll(Size(56, 24)),
                                                    padding: const WidgetStatePropertyAll(
                                                        EdgeInsets.zero),
                                                    alignment: Alignment.center,
                                                    backgroundColor: WidgetStatePropertyAll(
                                                        key == controller.typeIndex.value
                                                            ? Colors.white
                                                            : Colors.transparent),
                                                    shape: WidgetStatePropertyAll(
                                                        RoundedRectangleBorder(
                                                            borderRadius:
                                                                BorderRadius.circular(12)))),
                                                child: Text(
                                                  value,
                                                  style: StylesUtils.customTextStyle(
                                                      color: key == controller.typeIndex.value
                                                          ? ColorsUtils.colorE854
                                                          : ColorsUtils.colorFfff,
                                                      fontSize: StylesUtils.fontSize13),
                                                ),
                                              ))))
                                      .values
                                      .toList(),
                                ),
                                IconButton(
                                    onPressed: () {},
                                    icon: SvgUtils.assetName('u9252', width: 15, height: 15))
                              ],
                            ),
                          );
                        }),
                    pinned: true,
                  ),
                  maintainState: true,
                  maintainAnimation: true,
                  visible: controller.controller.index == 1,
                ),
              ];
            },
            body: TabBarView(
              controller: controller.controller,
              children: [
                KeepAliveWrapperTabView(
                  child: const StoreMainView(),
                  callback: () {
                    Get.put(StoreMainController());
                  },
                ),
                KeepAliveWrapperTabView(
                  child: const StoreBabyView(),
                  callback: () {
                    Get.put(StoreBabyController());
                  },
                ),
                KeepAliveWrapperTabView(
                  child: const StoreNewView(),
                  callback: () {
                    Get.put(StoreNewController());
                  },
                ),
                KeepAliveWrapperTabView(
                  child: const StoreGoodView(),
                  callback: () {
                    Get.put(StoreGoodController());
                  },
                ),
                KeepAliveWrapperTabView(
                  child: const StoreActivityView(),
                  callback: () {
                    Get.put(StoreActivityController());
                  },
                ),
              ],
            ),
          ),
        ));
  }

  Widget get tabBar {
    return ToolsUtils.getClientTabBar(controller.tabs, controller.controller,
        labelColor: ColorsUtils.colorFfff,
        unselectedLabelColor: ColorsUtils.colorFfff,
        isScrollable: false,
        indicatorColor: ColorsUtils.colorFfff);
  }
}

class _SliverHeaderDelegate extends SliverPersistentHeaderDelegate {
  /// child 为 header
  _SliverHeaderDelegate({
    required this.maxHeight,
    this.minHeight = 0,
    required Widget child,
  })  : builder = ((a, b, c) => child),
        assert(minHeight <= maxHeight && minHeight >= 0);

  ///最大和最小高度相同
  _SliverHeaderDelegate.fixedHeight({
    required double height,
    required Widget child,
  })  : builder = ((a, b, c) => child),
        maxHeight = height,
        minHeight = height;

  ///需要自定义builder时使用
  _SliverHeaderDelegate.builder({
    required this.maxHeight,
    this.minHeight = 0,
    required this.builder,
  });

  final double maxHeight;
  final double minHeight;
  final SliverHeaderBuilder builder;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    Widget child = builder(context, shrinkOffset, overlapsContent);
    //测试代码：如果在调试模式，且子组件设置了key，则打印日志
    assert(() {
      if (child.key != null) {
        debugPrint('${child.key}: shrink: $shrinkOffset，overlaps:$overlapsContent');
      }
      return true;
    }());
    // 让 header 尽可能充满限制的空间；宽度为 Viewport 宽度，
    // 高度随着用户滑动在[minHeight,maxHeight]之间变化。
    return SizedBox.expand(child: child);
  }

  @override
  double get maxExtent => maxHeight;

  @override
  double get minExtent => minHeight;

  @override
  bool shouldRebuild(_SliverHeaderDelegate old) {
    return old.maxExtent != maxExtent || old.minExtent != minExtent;
  }
}
